package ucadminlogic

import (
	"context"
	"go.uber.org/zap"
	"navi-mumbai/app/rpc/model/pg/usercenter"
	"navi-mumbai/common/key/dbkey"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"
	"strings"
	"time"

	"navi-mumbai/app/rpc/usercenter/internal/svc"
	"navi-mumbai/app/rpc/usercenter/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type QueryFeedbackListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewQueryFeedbackListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryFeedbackListLogic {
	return &QueryFeedbackListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 查询用户反馈列表
func (l *QueryFeedbackListLogic) QueryFeedbackList(in *pb.QueryFeedbackListReq) (*pb.QueryFeedbackListResp, error) {
	defer utils.RecoverPanic()

	var start, end *time.Time
	if in.StartTime != "" {
		loc, _ := time.LoadLocation(dbkey.DateTimeZone)
		t, err := time.ParseInLocation(dbkey.DateTimeCNFormat, in.StartTime, loc)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, "date format error")
		}
		start = &t
	}
	if in.EndTime != "" {
		loc, _ := time.LoadLocation(dbkey.DateTimeZone)
		t, err := time.ParseInLocation(dbkey.DateTimeCNFormat, in.EndTime, loc)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, "date format error")
		}
		end = &t
	}
	var err error
	var list []*usercenter.UserFeedback
	list, err = l.svcCtx.UserFeedbackModel.Find(l.ctx, in.Uid, in.State, start, end, in.PageNo, in.PageSize)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}

	var resp pb.QueryFeedbackListResp
	resp.List = make([]*pb.Feedback, 0)

	if len(list) <= 0 {
		return &resp, nil
	}

	if in.PageNo <= 1 {
		resp.Total, err = l.svcCtx.UserFeedbackModel.Count(l.ctx, in.Uid, in.State, start, end)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
		}
	}

	for i := 0; i < len(list); i++ {
		var vl pb.Feedback
		vl.Id = list[i].Id
		vl.Uid = list[i].Uid
		vl.Content = list[i].Content
		vl.CreateTime = list[i].CreateTime.Format(dbkey.DateTimeCNFormat)
		vl.Attachments = strings.Split(list[i].Attachments, "#")
		vl.ReplyAttachments = strings.Split(list[i].ReplyAttachments, "#")
		vl.Reply = list[i].Reply
		if list[i].ReplyTime.Valid {
			vl.ReplyTime = list[i].ReplyTime.Time.Format(dbkey.DateTimeCNFormat)
		}
		vl.State = list[i].State
		resp.List = append(resp.List, &vl)
	}
	return &resp, nil
}
